package com.wxy.netty.黏包半包处理;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

/**解决方法：
 * 1.短连接：服务端发送一次消息后立即关闭连接 解决了黏包问题 但是如果服务端的netty缓冲区大小过小会半包
 * @author 47868
 */
public class Client {
    public static void main(String[] args) throws Exception {
        for (int i = 0;i < 10;i++){
            send();
        }
        System.out.println("finish");
    }
    public static void send() throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ChannelFuture future = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new StringEncoder());
                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            //channel创建成功后自动触发channelActive方法
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                ByteBuf byteBuf = ctx.alloc().buffer();
                                byteBuf.writeBytes(new byte[]{1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1});
                                ctx.writeAndFlush(byteBuf);
                                ctx.close();
                            }
                        });
                    }
                })
                .connect("127.0.0.1", 8888);
        Channel channel = future.sync().channel();
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener((ChannelFutureListener) channelFuture -> eventLoopGroup.shutdownGracefully());
    }
}
